﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using finalProjectGUI;
using System.Collections;
using ZedGraph;


namespace FinalProjectLogicLayerINTERFACE
{
    public partial class mainFrame : Form
    {
        private LogicLayerImplementation cipherTextAnalysisLogicLayer = new LogicLayerImplementation(); //instance of the logiclayer implementation
        private ArrayList listOfFilesInProcess = new ArrayList(); // arraylist for storing files in process needed to match logiclayer implementation API
        private int numberOfClustersInProcess = 0;
        private Boolean loadingFileDeatails = false;
        ArrayList clusteringResults = null;
        private String[] lablesInResults;
        private int[] defaultSettings = new int[5];// default settings [0] - dictionarySize, [1] - wordLength, [2] - matching Distance, [3] - distance mesurment, [4] - number of clusters
        public mainFrame()
        {
            InitializeComponent();
            cipherTextAnalysisLogicLayer.ProgramProgresBar = progressBarProcessStatus;
            cipherTextAnalysisLogicLayer.ToolStripStatusLabel = labelProcessStatus;
            //populate the distances combobox for clustering method
            foreach (string item in Enum.GetNames(typeof(Clustering.DistanceMeasurement)))
            {
            comboBoxDistanceCalculationMethod.Items.Add( item );
                //EuclidianDistance,
                //ManhattanDistance,
                //MaxDistance,
                //KS_LikeDistance,
                //CorreleationDissimilarity,
                //PearsonDissimilarity,
                //SpearmanDissimilarity,
                //KendallRandDIssimilarity
            }
            buttonClusterFiles.Enabled = false;
            comboBoxDistanceCalculationMethod.SelectedIndex = (int)Clustering.DistanceMeasurement.ManhattanDistance;
            //populate labels at listboxLabels and comboboxLabels
            String[] loadedLables = cipherTextAnalysisLogicLayer.getLabels();
            if (loadedLables != null) //if opend the file succesfully
            {
                if (loadedLables.Length>0)
                    if (loadedLables[0] != "") 
                        listBoxFileLabels.Items.AddRange(cipherTextAnalysisLogicLayer.getLabels()); //Load saved lables
            }
            for (int i = 0; i < 9; i++)
            {
                comboBoxAlphaBetSize.Items.Add(1<<i);
            }
            comboBoxAlphaBetSize.SelectedIndex = comboBoxAlphaBetSize.Items.Count - 1;

            //Save default Status and reflect settings to logicLayer
            cipherTextAnalysisLogicLayer.DictionarySize                  =  defaultSettings[0] = (int) numericUpDownDictionarySize.Value;
            cipherTextAnalysisLogicLayer.DictionaryWordSize              =  defaultSettings[1] = (int) numericUpDownDictionaryWordLength.Value;
            cipherTextAnalysisLogicLayer.StringMatchingErrorsAllowed     = defaultSettings[2] = (int)numericUpDownStringMatchingErrors.Value;
            defaultSettings[3] = comboBoxDistanceCalculationMethod.SelectedIndex;
            cipherTextAnalysisLogicLayer.VectorDistanceCalculationMethod = (Clustering.DistanceMeasurement)Enum.Parse(typeof(Clustering.DistanceMeasurement), comboBoxDistanceCalculationMethod.SelectedItem.ToString(), true);
            cipherTextAnalysisLogicLayer.NumberOfClusters                =  defaultSettings[4] = (int) numericUpDownNumberOfClusters.Value;
            

            foreach (string item in listBoxFileLabels.Items)
            {
                comboBoxFileLabels.Items.Add(item);
            }
           // GuiZedGraph.CreateGraph2(zg1);
        }
        

        /// <summary>
        /// This method adds a new file to the analysis
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonAddInputFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            openFileDialog.Title = "Choose a file";
            openFileDialog.Filter = "Text Files|*.txt| Rijndael files|*.rij| All files|*.*";
            openFileDialog.CheckFileExists = true;
            openFileDialog.CheckPathExists = true;
            openFileDialog.Multiselect = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (cipherTextAnalysisLogicLayer.addFileToProcess(openFileDialog.FileName.ToString())) //add file to logiclayer
                {//if the file was added to logicLayer
                    foreach (String fileName in openFileDialog.SafeFileNames) //add only file name to list
                    {
                        listBoxInputFiles.Items.Add(fileName);
                    }
                    foreach (String fileName in openFileDialog.FileNames) //add full path to logic layer
                    {
                        cipherTextAnalysisLogicLayer.addFileToProcess(fileName);
                        listOfFilesInProcess.Add(fileName); //keep a list of full file paths in GUI
                    }

                }
            }
            
        }
        /// <summary>
        /// This method removes a file from the process
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonRemoveInputFile_Click(object sender, EventArgs e)
        {
            if (listBoxInputFiles.SelectedIndex >= 0)
            {
                cipherTextAnalysisLogicLayer.removeFileFromProcess(listOfFilesInProcess[(listBoxInputFiles.SelectedIndex)].ToString()); //Remove file from logiclayer (send full path)
                listOfFilesInProcess.RemoveAt(listBoxInputFiles.SelectedIndex); //remove from list of files in process
                listBoxInputFiles.Items.RemoveAt(listBoxInputFiles.SelectedIndex); //remove from gui listbox
            }
        }
        private void updateLables()
        {
            String lables = "";
            foreach (String lable in listBoxFileLabels.Items)
                lables += lable + ",";
            if (lables != "") //remove last ,
                lables = lables.Substring(0, lables.LastIndexOf(','));
            cipherTextAnalysisLogicLayer.updateLables(lables);
        }
        private void buttonAddFileLabels_Click(object sender, EventArgs e)
        {
            InputMessageDialog inputMessageDialog = new InputMessageDialog("NEW LABEL DIALOG", "New label:");
            if (inputMessageDialog.ShowDialog() == DialogResult.OK)
            {
                if (inputMessageDialog.Input != "")
                {
                    listBoxFileLabels.Items.Add(inputMessageDialog.Input);
                    comboBoxFileLabels.Items.Add(inputMessageDialog.Input);
                    updateLables();
                }
            }
        }

        private void buttonRemoveFileLabel_Click(object sender, EventArgs e)
        {
            if (listBoxFileLabels.SelectedIndex >= 0)
            {

                int indexToRemove = listBoxFileLabels.SelectedIndex;
                cipherTextAnalysisLogicLayer.removeLabel(listBoxFileLabels.SelectedItem.ToString());
                listBoxFileLabels.Items.RemoveAt(indexToRemove);
                comboBoxFileLabels.Items.RemoveAt(indexToRemove);
                updateLables();
            }
        }

        /// <summary>
        /// This method allows to choose a different source file for the dictionary creation algorithem
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonChangeDictionarySourceFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Title = "Choose a file";
            openFileDialog.Filter = "Text Files|*.txt| All files|*.*";
            openFileDialog.CheckFileExists = true;
            openFileDialog.CheckPathExists = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                labelSelectedDictionarySource.Text = openFileDialog.FileName.ToString().Substring(openFileDialog.FileName.ToString().LastIndexOf('\\') + 1);
                cipherTextAnalysisLogicLayer.DictionarySourceFile = openFileDialog.FileName.ToString(); //update logiclayer
                toolTipMainFrame.SetToolTip(labelSelectedDictionarySource, openFileDialog.FileName.ToString()); //TODO CHECK TOOLTIPS...
                buttonClusterFiles.Enabled = true;
            }
        }

        /// <summary>
        /// This method updates logic layer about the change in the numeric value of the dictionary size
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void numericUpDownDictionarySize_ValueChanged(object sender, EventArgs e)
        {
            cipherTextAnalysisLogicLayer.DictionarySize = (int) numericUpDownDictionarySize.Value;
        }

        /// <summary>
        /// This method updates logic layer about the change in the numeric value of the dictionary Word length
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void numericUpDownDictionaryWordLength_ValueChanged(object sender, EventArgs e)
        {
            cipherTextAnalysisLogicLayer.DictionaryWordSize = (int) numericUpDownDictionaryWordLength.Value;
        }

        /// <summary>
        /// This method enables or disables the file setting and gets the setting for the selected
        /// file in the listBox of the input files
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBoxInputFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBoxInputFiles.SelectedIndex == -1) //No file is selected
            {
                //Disable and clear fields
                numericUpDownDevideFileParameter.Enabled = false;
                comboBoxFileLabels.Enabled = false;
                textBoxInputFileComments.Enabled = false;
                numericUpDownDevideFileParameter.Value = 1;
                comboBoxFileLabels.SelectedItem = -1;
                textBoxInputFileComments.Text = "";

            }
            else
            {
                loadingFileDeatails = true;
                numericUpDownDevideFileParameter.Enabled = true;
                comboBoxFileLabels.Enabled = true;
                textBoxInputFileComments.Enabled = true;
                cipherTextAnalysisLogicLayer.setSelectedFile(listOfFilesInProcess[(listBoxInputFiles.SelectedIndex)].ToString());
                
                //update labels in file information to the selected file information 
                textBoxInputFileComments.Text = cipherTextAnalysisLogicLayer.SelectedFileComments;
                comboBoxFileLabels.SelectedIndex = comboBoxFileLabels.Items.IndexOf(cipherTextAnalysisLogicLayer.SelectedFileLabel);
                numericUpDownDevideFileParameter.Value = cipherTextAnalysisLogicLayer.SelectedFileDevisionParameter;               
                loadingFileDeatails = false;
                
            }
        }

        /// <summary>
        /// This method updates logic layer about the change in the numeric value of the String Matching degree of distance 
        /// between strings
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void numericUpDownStringMatchingErrors_ValueChanged(object sender, EventArgs e)
        {
            cipherTextAnalysisLogicLayer.StringMatchingErrorsAllowed = (int) numericUpDownStringMatchingErrors.Value;
        }

        /// <summary>
        /// This method updates logic layer about the change in the numeric value of the number of clusters
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void numericUpDownNumberOfClusters_ValueChanged(object sender, EventArgs e)
        {
            cipherTextAnalysisLogicLayer.NumberOfClusters = (int)numericUpDownNumberOfClusters.Value;
        }

        private void comboBoxDistanceCalculationMethod_SelectedIndexChanged(object sender, EventArgs e)
        {
            cipherTextAnalysisLogicLayer.VectorDistanceCalculationMethod = (Clustering.DistanceMeasurement)comboBoxDistanceCalculationMethod.SelectedIndex;
        }

        private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            cipherTextAnalysisAboutBox aboutbox = new cipherTextAnalysisAboutBox();
            
            
            
            aboutbox.ShowDialog();
        }
        /// <summary>
        /// SELECTED FILE COMMENTS TEXT CHANGED
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxInputFileComments_TextChanged(object sender, EventArgs e)
        {
            if (loadingFileDeatails == true) return; //if we are forcing the change
            cipherTextAnalysisLogicLayer.SelectedFileComments = textBoxInputFileComments.Text;
        }
        /// <summary>
        /// SELECTED INDEX OF FILE LABELS CHANGED
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxFileLabels_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (loadingFileDeatails == true) return; //if we are forcing the change
            if (comboBoxFileLabels.SelectedIndex > -1)
                cipherTextAnalysisLogicLayer.SelectedFileLabel = comboBoxFileLabels.SelectedItem.ToString();
                
        }
        /// <summary>
        /// SELECTED NUMBER IN NUMERICAL UP DOWN FOR FILE DEVISION PARAMETER CHANGED
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void numericUpDownDevideFileParameter_ValueChanged(object sender, EventArgs e)
        {
            if (loadingFileDeatails == true) return; //if we are forcing the change
            cipherTextAnalysisLogicLayer.SelectedFileDevisionParameter = (int) numericUpDownDevideFileParameter.Value;
        }

        
        private void buttonClusterFiles_Click(object sender, EventArgs e)
        {
            this.Enabled = false;

            DateTime startTime = DateTime.Now;
            
            cipherTextAnalysisLogicLayer.extractFeatures();
            clusteringResults = cipherTextAnalysisLogicLayer.calulateClusters(); //Calculate clusters

            DateTime stopTime = DateTime.Now;
            TimeSpan duration = stopTime - startTime;

            this.Enabled = true;
            labelProcessStatus.Text = "Done. in " + duration; 
            labelProcessStatus.Update();
            guiClusteringResults clusteringResultsForGraph = new guiClusteringResults();
            numberOfClustersInProcess = 0;
            int clusterNumber = 0;
                        
            ArrayList fileLableList = new ArrayList();

            foreach (FinalProjectLogicLayer.DataPoint[] cluster in clusteringResults)
            {
                if (cluster.Length == 0) continue;
                
                for (int i = 0; i < cluster.Length; i++)
                {
                    
                    clusteringResultsForGraph.inc(clusterNumber, cluster[i].Label);
                }
                clusterNumber++;
                numberOfClustersInProcess++;
            }
            
            GuiZedGraph.CreateClusteringResultsGraph(zg1, clusteringResultsForGraph);

            
         
            //**  Create clustering results table **
            lablesInResults = clusteringResultsForGraph.getLables(); //lables in the process
            int numberOfLables = lablesInResults.Length; //number of lables as input to the process
            int numberOfClusters = clusteringResults.Count; //number of clsters in results
            String[,] resultsTableStrings = new String[numberOfLables,numberOfClusters];
            int clusterNum = -1;
            foreach (FinalProjectLogicLayer.DataPoint[] cluster in clusteringResults)
            {
                clusterNum++;

                for (int i = 0; i < cluster.Length; i++)
                {
                    int labelIndex = indexOfStringInArray(lablesInResults, cluster[i].Label); //Index of the current data point's label
                    resultsTableStrings[labelIndex, clusterNum] += cluster[i].SourceFile.Substring(cluster[i].SourceFile.LastIndexOf('\\') + 1)  +  ",";
                }


            }

            //resultsTableStrings is ready in this stage
            String htmlResultsTabel = FinalProjectLogicLayer.HtmlReport.createHtmlClusteringResultsTabel(resultsTableStrings, lablesInResults);

            webBrowserResults.DocumentText = htmlResultsTabel;
            tabControlSettings.SelectedTab = tabPageGraph; //graphical Results Tab
        }

        private int indexOfStringInArray(String[] stringArray, String find)
        {
            for (int i = 0; i < stringArray.Length; i++)
            {
                if (stringArray[i] == find)
                    return i;
            }
            return -1;
        }
        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cipherTextAnalysisLogicLayer.saveFile();
            this.Text = "Cipher text analysis using compositional spectrum      " + cipherTextAnalysisLogicLayer.SaveFileName;
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "Save file as";
            saveFileDialog.Filter = "Save File|*.xml";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                cipherTextAnalysisLogicLayer.SaveFileName = saveFileDialog.FileName.ToString(); //update logiclayer
                this.Text = "Cipher text analysis using compositional spectrum      " + cipherTextAnalysisLogicLayer.SaveFileName;
                cipherTextAnalysisLogicLayer.saveFile();
            }

            

        }



        private void loadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog loadFileDialog = new OpenFileDialog();
            loadFileDialog.Title = "Load file";
            loadFileDialog.Filter = "Save File|*.xml";
            if (loadFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {

                    cipherTextAnalysisLogicLayer.loadFile(loadFileDialog.FileName);
                }
                catch 
                {
                    loadingFileDeatails = false;
                    MessageBox.Show("ERROR OPENING FILE: WRONG FILE TYPE OR CORRUPTED", "FILE OPENING ERROR", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
                    return;
                }
                    loadingFileDeatails = true;
                    //Reload lables.. or something
                    //LIST OF FILES
                    listBoxInputFiles.ClearSelected();
                    listBoxInputFiles.Items.Clear();
                    listOfFilesInProcess.Clear();
                    //clear results
                    zg1.GraphPane.CurveList.Clear(); 
                    

                    foreach (String fileName in cipherTextAnalysisLogicLayer.getListOfFilesInProcess())
                    {
                        listOfFilesInProcess.Add(fileName);
                        listBoxInputFiles.Items.Add(fileName.Substring(fileName.LastIndexOf('\\') + 1));
                    }

                    //Dictionary
                    numericUpDownDictionarySize.Value = cipherTextAnalysisLogicLayer.DictionarySize;
                    numericUpDownDictionaryWordLength.Value = cipherTextAnalysisLogicLayer.DictionaryWordSize;
                    labelSelectedDictionarySource.Text = cipherTextAnalysisLogicLayer.DictionarySourceFile;
                    comboBoxAlphaBetSize.SelectedItem = cipherTextAnalysisLogicLayer.AlphaBetSize;

                    if (labelSelectedDictionarySource.Text != "")
                        buttonClusterFiles.Enabled = true;
                    else
                        buttonClusterFiles.Enabled = false;
                    toolTipMainFrame.SetToolTip(labelSelectedDictionarySource, labelSelectedDictionarySource.Text);
                    labelSelectedDictionarySource.Text = labelSelectedDictionarySource.Text.Substring(labelSelectedDictionarySource.Text.LastIndexOf('\\') + 1);
                    this.Text = "Cipher text analysis using compositional spectrum      " + loadFileDialog.SafeFileName;
                    //StringMatching
                    numericUpDownStringMatchingErrors.Value = cipherTextAnalysisLogicLayer.StringMatchingErrorsAllowed;

                    //Clustering
                    numericUpDownNumberOfClusters.Value = cipherTextAnalysisLogicLayer.NumberOfClusters;
                    comboBoxDistanceCalculationMethod.SelectedValue = cipherTextAnalysisLogicLayer.VectorDistanceCalculationMethod.ToString();

                    loadingFileDeatails = false;

            }

        }
        /// <summary>
        /// This methods creats a new process
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure? current process will be deleted", "NEW", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk) == DialogResult.OK)
            {
                loadingFileDeatails = true;
                //Reload lables.. or something
                //LIST OF FILES
                cipherTextAnalysisLogicLayer.newFile();
                listBoxInputFiles.ClearSelected();
                listBoxInputFiles.Items.Clear();
                listOfFilesInProcess.Clear();
                zg1.GraphPane.CurveList.Clear();
                
                foreach (String fileName in cipherTextAnalysisLogicLayer.getListOfFilesInProcess())
                {
                    listOfFilesInProcess.Add(fileName);
                    listBoxInputFiles.Items.Add(fileName.Substring(fileName.LastIndexOf('\\') + 1));
                }
                
                
                
                //Dictionary
                 numericUpDownDictionarySize.Value = defaultSettings[0];
                 numericUpDownDictionaryWordLength.Value = defaultSettings[1];

                labelSelectedDictionarySource.Text = cipherTextAnalysisLogicLayer.DictionarySourceFile;
                toolTipMainFrame.SetToolTip(labelSelectedDictionarySource, "");              
                this.Text = "Cipher text analysis using compositional spectrum      ";
                //StringMatching
                numericUpDownStringMatchingErrors.Value = defaultSettings[2];
                //Clustering
                comboBoxDistanceCalculationMethod.SelectedIndex = defaultSettings[3];
                numericUpDownNumberOfClusters.Value = defaultSettings[4];
                

                loadingFileDeatails = false;
            }
        }

        private void tabPageSettings_Click(object sender, EventArgs e)
        {
            return;
        }
        /***********************************************************/
        private void tabPageGraph_Click(object sender, EventArgs e)
        {
            //GuiZedGraph.CreateGraph2(zg1);
        }

        

        private void SetSize()
        {
            zg1.Location = new Point(200, 10);
            // Leave a small margin around the outside of the control
            zg1.Size = new Size(this.ClientRectangle.Width - 210, this.ClientRectangle.Height - 90);
        }

        private void mainFrame_Load(object sender, EventArgs e)
        {
            SetSize();
        }

        private void tabPageGraph_Resize(object sender, EventArgs e)
        {
            SetSize();
        }

        private void comboBoxClusterSelection_SelectedIndexChanged(object sender, EventArgs e)
        {
        
        }

 


        private void buttonShowClusterDetails_Click(object sender, EventArgs e)
        {

        if (clusteringResults==null)
                    MessageBox.Show(" There are no clustering results to report about ", "ERROR!!", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
        else
        {
            new System.Threading.Thread (showClusterDeatils).Start(); //Run the cluster details gui on a seperate thread
         }
         
        }
        private void showClusterDeatils()
        {
            ClusterDetailsGui clusterGui = new ClusterDetailsGui();
            clusterGui.ClusteringResults = clusteringResults;
            // clusterGui.createGraph(0);
            clusterGui.ResultsLables = lablesInResults;

            clusterGui.createClusterDetailsGraph(0);
            //System.Threading.Thread
            clusterGui.ShowDialog();
        }
        /// <summary>
        /// This method generates all graphs for the HTML report file
        /// </summary>
        /// <param name="filePath">Path of the html file</param>
        private void generateAllGraphs(String filePath)
        {
            if (numberOfClustersInProcess > 0)
            {
                filePath = filePath.Substring(0, filePath.LastIndexOf('.')) + "\\";
                System.IO.Directory.CreateDirectory(filePath);
            }

            ClusterDetailsGui clusterGui = new ClusterDetailsGui();
            clusterGui.ClusteringResults = clusteringResults;
            clusterGui.ResultsLables = lablesInResults;

            for (int selectedIndex = 0; selectedIndex < numberOfClustersInProcess; selectedIndex++)
            {              
                    clusterGui.createClusterDetailsGraph(selectedIndex);
                    clusterGui.GraphControl.GraphPane.GetImage().Save(filePath+"CLUSTER"+(selectedIndex+1)+".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                    clusterGui.createGraph(selectedIndex);
                    clusterGui.GraphControl.GraphPane.GetImage().Save(filePath + "CLUSTERD" + (selectedIndex + 1) + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                }

            zg1.GraphPane.GetImage().Save(filePath + "CLUSTERING_RESULT.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
           
        }


        private void comboBoxAlphaBetSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            cipherTextAnalysisLogicLayer.AlphaBetSize = (int)comboBoxAlphaBetSize.Items[comboBoxAlphaBetSize.SelectedIndex];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonGenerateReport_Click(object sender, EventArgs e)
        {
            generateReport();
        }

        /// <summary>
        /// 
        /// </summary>
        private void generateReport()
        {

            if (clusteringResults != null)
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title = "Save file as";
                saveFileDialog.Filter = "Save File|*.html";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    cipherTextAnalysisLogicLayer.SaveFileName = saveFileDialog.FileName.ToString(); //update logiclayer
                    generateAllGraphs(saveFileDialog.FileName);
                    cipherTextAnalysisLogicLayer.generateReport(saveFileDialog.FileName, clusteringResults);
                }
            }
            else
            {
                MessageBox.Show(" There are no clustering results to report about ", "ERROR!!", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }

        }

        private void textFileForMatlabToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (clusteringResults != null)
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                saveFileDialog.Title = "Export CSV's to matlab as text";
                saveFileDialog.Filter = "Save File|*.txt";
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    cipherTextAnalysisLogicLayer.exportToTextFileForMatlab(saveFileDialog.FileName.ToString()); //Use logic layer method to export the data
                }
            }
            else
            {
                MessageBox.Show(" No CSV's where calculated yet ", "ERROR!!", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }

            
        }

        private void htmlReportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            generateReport();
        }

        private void helpToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Help.ShowHelp(this,System.Environment.CurrentDirectory+"//ciphertextanalysishelp.chm");
            
        }




    }
}
